<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ModelController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class System_ModelController extends Baogg_Controller_Action {

	function init() {
		Zend_Loader::loadClass ( 'Model' );
		$this->model = new Model ( );

		BAOGG_LANGUAGE::loadFile('model');
		BAOGG_LANGUAGE::loadFile('rule');
	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;		
		$params=$this->getRequest()->getParams();
		$form_url=$params;
		Zend_Loader::loadClass("Baogg_View_Extgrid");
		
		$cm=array();
		$cm['model_id']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_PK) ;
		$cm['model_name']=array("sortable"=>true);
		$cm['table_name']=array("sortable"=>true);
		$cm['db_key']=array("sortable"=>true);
		//$cm['main_table']=array("sortable"=>true);
		//$cm['ext_table']=array("sortable"=>true);
		$cm['form_height']=array("sortable"=>true,"width"=>30);
		$cm['menu_id']=array("hidden"=>true);
		$cm['rule_id']=array("hidden"=>true);	
		//$cm['rule_name']=array("sortable"=>false);
		$cm['description']=array("sortable"=>true);		
		$cm['state']=array("sortable"=>true,"width"=>30);
		$cm['ordering']=array("sortable"=>true,"width"=>30);		
		//$cm['action']=array("sortable"=>true);
		//$cm['relation_id']=array("hidden"=>true);
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;
		
		$form_url['action']="data";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);
		$grid->addExistButtons(array('add','remove','query'),array('edit','delete','relation_in_model','model_field','model_detail','gen'));//
	//$grid->registerButton("model_fields","window.location.href='".BAOGG_BASE_URL."system/multimodelfield/list/relation_id/{$this->relation_id}/';");
		
		//$form_url=BAOGG_BASE_URL."system/multimodel/";//#action#/relation_id/".$this->relation_id;
		
		$form_url['action']='add';
		$form=new Baogg_View_Extform(array("url"=>$form_url,"height"=>300,"width"=>600));
		
		$form->addItem(0,array('name'=>'model_name'));		
		$form->addItem(0,array('name'=>'table_name'));	
		$form->addItem(0,array('name'=>'db_key'));
					
		$form->addItem(1,array('name'=>'form_height'));
		$form->addItem(1,array('name'=>'description'));
		
		$arr_menu=array(array('0',BAOGG_LANGUAGE::get('please_select')));
		$Menu=new Menu();
		$rs_menu=$arr_menu+$Menu->getComboTree(array("state"=>1),array("sort"=>"ordering","dir"=>"asc"),NULL,array('menu_id','menu_name','menu_pid'));			
		$form->addItem(1,array('name'=>'menu_id','xtype'=>'combo','store'=>$rs_menu));
		
		$arr_rule=array(array('0',BAOGG_LANGUAGE::get('please_select')));
		$Rule=new Rule();
		$rs_rule=$Rule->getList(array("state"=>1),array("sort"=>"ordering","dir"=>"asc"));
		foreach((array)$rs_rule as $v){
			$arr_rule[]=array($v['rule_id'],$v['rule_name']);
		}		
		$form->addItem(1,array('name'=>'rule_id','xtype'=>'combo','store'=>$arr_rule));
		
		$form->addItem(2,array('name'=>'state','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));		
		$form->addItem(2,array('name'=>'ordering'));
		
		//$form->addItem(2,array('name'=>'relation_id',"xtype"=>"hidden","hideLabel"=>true,"value"=>$this->relation_id));
		$form->addItem(2,array('name'=>'model_id',"xtype"=>"hidden","hideLabel"=>true));		
		$form->addExistButtons(array('-','save_grid','save_new','save','-','search','-','cancel'));//,'config','config'
		
		$this->view->form=$form;
		
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();
		
		//echo '<pre>';var_dump($LANG);exit;


	}

	/**
	 * The data action
	 */
	function dataAction() {
		global $LANG;
	    $post=$this->_request->getPost ();
	    $where=array();$order=array();$limit=array();
	   foreach((array)$post as $k=>$v){
	       if($k=="start" || $k=="limit"){
	           $limit[$k]=$v;
	       }else if($k=="sort" || $k=="dir"){
	           $order[$k]=$v;
	       }else{
	           if($k=="model_id"  ){
	               if($v && is_numeric($v)){
	                   $v=(int)$v;
	                   $where[$k]=$v;
	               }
	           }else if($k=="query"){
	           		$where[]="(model_name like '%{$v}%' or table_name like '%{$v}%' )";
	           } else{
	               $v='%'.$v.'%';
	               $where[$k]=$v;
	           }
	           
	       }
	   }
	   if(!$order){
	   	$order['sort']='ordering';
	   	$order['dir']='asc';
	   }
	  // $where['relation_id']=1;
        $rs=$this->model->getList($where,$order,$limit);
         $rs_cnt=$this->model->getList($where,$order,NULL,"count(*) as cnt");
        /*foreach((array)$rs as $k=>$v){
        	$rs[$k]['action']='<a href="'.BAOGG_BASE_URL.'system/multimodelfield/list/model_id/'.$v['model_id'].'/relation_id/'.$this->relation_id.'"><img src="'.BAOGG_THEME.'images/action/edit.png" title="'.Baogg_Language::get('model_field').'" /></a>';
        }*/
        
		echo  Zend_Json::encode(array("count"=>$rs_cnt[0]['cnt'],"data"=>$rs));
		Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);
		
	}

	
	/**
	 * The add action
	 */
	function addAction(){	
		$this->saveAction();

	}
	
	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();	
	}
	
	function removeAction(){
		$this->deleteAction();
	}
	/**
	 * The delete action
	 */
	function deleteAction() {
        
	    $ret=array("success"=>false,"msg"=>"delete_fail");
	    $id = Baogg_Controller_Action::_getParam ( 'ids' );
		 
		$ModelField=new ModelField();   
		
		if ($this->model->_delete ( $id ) && $ModelField->delete(array("model_id"=>$id))){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		 Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);
		/*$this->_helper->viewRenderer->setNoRender ();
		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= debugDb();
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
		insertLog($log);*/
		
		
	}

	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		
	    $ret=array("success"=>false,"msg"=>"save_fail");
	    
	    //check form
		if (!$this->_request->isPost ())
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;
		}
		
		$formData = $this->_request->getPost ();

		if(!$formData)
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;     
		}
		$action=$this->getRequest()->getParam("action");	
		$arr=$this->model->filterForm($formData);
        
		$rs = $this->model->getSame($arr);
		
		if(is_array($rs) && count($rs)>0){		
			$ret['msg'] = "exist_same_record";
			echo Baogg_Language::outputResult($ret);
            exit;
		}
		
		if($action=='edit'){
			$rs_old=$this->model->getOne($arr["model_id"]);
			$old_name=$rs_old[0]['table_name'];
							
		    $this->model->_update($arr,$arr["model_id"]);
		    
		    if($old_name!=$arr['table_name']){
		      $this->model->changeTable($old_name,$arr['table_name']);		      
		    }
		    $flag=$this->model->initTable($arr["model_id"]);
		    $flag=$this->model->genExtPkTable($arr["model_id"]);
		    $ret['success'] = true;				
			$ret['msg'] = "save_ok";		
		}else{			
			//echo '<pre>';print_r($arr);exit;
			$model_id=$this->model->_insert($arr);
			$flag=$this->model->initTable($model_id);
			$flag=$this->model->genExtPkTable($model_id);
			$ret['success'] = $flag;
			$ret['msg'] = "add_ok";
		}
				
		echo Baogg_Language::outputResult($ret);
		
		$this->_helper->viewRenderer->setNoRender ();
		
		
	}
	
	function viewAction() {
		$model_id=(int)$this->getRequest()->getParam("model_id");
		$rs_model=$this->model->getOne($model_id);
		if(!$model_id || !$rs_model){
			echo "parameter model_id don't exist";
			exit;
		}
		
		$ModelField=new ModelField();
		$rs_model_field=$ModelField->getList(array("model_id"=>$model_id));
		$key_field="";
		$lable_field="";
		$parent_field="";
		foreach((array)$rs_model_field as $v){
			if($v['field_key']=='PRI'){
				$key_field=$v['field_name'];
			}
			if($v['is_label']){
				$lable_field=$v['field_name'];
			}
			if($v['is_parent']){
				$parent_field=$v['field_name'];
			}
		}
		
		global $LANG;
		$params=$this->getRequest()->getParams();
		$form_url=$params;
		Zend_Loader::loadClass("Baogg_View_Extgrid");
		
		$cm=array();
		$cm[$key_field]=array("cmType"=>Baogg_View_Extgrid::CMTYPE_PK,'text'=>BAOGG_LANGUAGE::get("id")) ;
		$cm[$lable_field]=array("sortable"=>true,'text'=>BAOGG_LANGUAGE::get("name"));
		
		
		$form_url['action']="viewdata";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		$grid->setSelectionModel(false);
		$grid->setRowNumberer(true);
		
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();
		
		
	}
	function viewdataAction() {
		$model_id=(int)$this->getRequest()->getParam("model_id");	
		$rs_model=$this->model->getOne($model_id);
		if(!$model_id || !$rs_model){
			echo "parameter model_id don't exist";
			exit;
		}
		
		$class_name="";
		if($rs_model[0]['db_key']){
			$class_name.=ucwords(str_replace("_"," ",$rs_model[0]['db_key'])).'_';			
		}		
		$class_name.=ucwords(str_replace("_"," ",$rs_model[0]['table_name']));
		$class_name=str_replace(" ","",$class_name);
		$instance=new $class_name();
		
		$rs=$instance->getList();	
		$rs_cnt=$instance->getList(null,null,NULL,"count(*) as cnt");
		
		echo Zend_Json::encode(array("count"=>$rs_cnt[0]['cnt'],"data"=>$rs));
		$this->_helper->viewRenderer->setNoRender();
		
	
	}

	function genAction(){
		$ret=array("success"=>false,"msg"=>"save_fail");
		$model_id =$this->getRequest()->getParam('ids');
		//echo $model_id;
		$Model=new Model();		
		if ($Model->genFile($model_id)){
			$ret['success'] = true;
			$ret["msg"]="save_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);
	}
}
